package com.yingma.common.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author ysf
 * @date 2020/2/13 14:00
 */
@Configuration
public class ShrioConfig {

    //ShiroFilterFactoryBean

    //DefaultWebSecurityManager

    //创建 realm 对象,需要自定义类


    /**
     * 凭证匹配器
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher=new HashedCredentialsMatcher();
        //md5加密一次
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(1);
        return hashedCredentialsMatcher;
    }

    /**
     * 自定义的realm 第一步
     * @return
     */
    @Bean
    public UserRealm userRealm(){
        UserRealm userRealm =new UserRealm();
        //userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return userRealm;
    }

    /**
     * 安全管理器  第二步
     * 注：使用shiro-spring-boot-starter 1.4时,返回类型是SecurityManager会报错,直接引用shiro-spring则不报错
     * @return
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager securityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        //关联 userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }







    /**
     * 第三步
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager securityManager){
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(securityManager);
        //设置登陆的请求
        //bean.setLoginUrl("/jcSysUser/login");
        //添加shiro的内置过滤器
        /**
         * anon :无需认证就可以访问
         * authc :必须认证了才能访问
         * user :必须拥有, "记住我" 的功能才能用
         * perms:拥有对某个资源的权限才能访问
         * role :拥有某个角色权限才能访问
         */
        Map<String,String> filterMap=new LinkedHashMap<>();
        //filterMap.put("/static/**","anon");
        //设置拦截权限   表明如果访问user下的页面必须通过认证,
        //filterMap.put("/user/*","authc");
        filterMap.put("/**", "authc");

        return bean;
    }





}
